package com.sxr.signature.impl;

import com.sxr.signature.SignRequest;
import com.sxr.signature.VerifyService;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
import java.util.Objects;

/**
 * 基于HMAC-SHA256的签名服务实现
 * 零第三方依赖，仅使用JDK8标准库
 *
 * @author SXR
 * @since 1.0.0
 */
public class HmacVerifyService implements VerifyService {

    private static final String HMAC_SHA256 = "HmacSHA256";

    public String generateSignature(SignRequest request) {
        if (request == null || request.getSecretKey() == null) {
            throw new IllegalArgumentException("SignRequest and secretKey cannot be null");
        }

        try {
            // 构建待签名字符串
            String stringToSign = request.buildStringToSign();

            // 使用HMAC-SHA256生成签名
            Mac mac = Mac.getInstance(HMAC_SHA256);
            SecretKeySpec secretKeySpec = new SecretKeySpec(
                request.getSecretKey().getBytes(StandardCharsets.UTF_8),
                HMAC_SHA256
            );
            mac.init(secretKeySpec);

            byte[] signatureBytes = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            return Base64.getEncoder().encodeToString(signatureBytes);

        } catch (NoSuchAlgorithmException | InvalidKeyException e) {
            throw new RuntimeException("Failed to generate signature", e);
        }
    }

    @Override
    public boolean verifySignature(SignRequest request, String signature) {
        return Objects.equals(generateSignature(request),signature);
    }
}
